
cmake_minimum_required (VERSION 2.6)
project (acquire)

option(DOWNLOAD_NEW_KEYS "Download and install new broker keys to the key database automatically" OFF)
option(INSECURE_TEST_KEYS "Use insecure keys that are distributed with the source for testing" OFF)
option(INSECURE_PASSWORDS "Use built-in passwords to provide on-disk encryption" OFF)
option(BUILD_STATIC_LIBRARIES "Build static AcquireLib library" OFF)
option(BUILD_SPECIAL_COMPUTE "Build the special compute executable for remote execution" ON)
option(BUILD_TESTS "Build the tests directory" ON)
option(LOG_MESSAGE_TO_FILE "Log messages to a temporary file, and not the screen" ON)

if (INSECURE_TEST_KEYS AND NOT INSECURE_PASSWORDS)
   message( FATAL_ERROR "Built-in passwords are required to decrypt the test keys. INSECURE_PASSWORDS must be turned ON." )
endif (INSECURE_TEST_KEYS AND NOT INSECURE_PASSWORDS)

set(DYNAMIC_LINKER "/lib64/ld-linux-x86-64.so.2" CACHE STRING "Dynamic linker definition for portability")

set(CMAKE_CXX_IGNORE_EXTENSIONS 1)

if ( CMAKE_BINARY_DIR STREQUAL CMAKE_SOURCE_DIR )
   message( STATUS "${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}" )
   message( FATAL_ERROR "You must run CMake in a different directory to the source!" )
endif ( CMAKE_BINARY_DIR STREQUAL CMAKE_SOURCE_DIR )

# Name of executable install dir
set (ACQUIRE_BIN "bin")
# Shared library install dir
set (ACQUIRE_LIBS "lib")
# Static library install dir
set (ACQUIRE_ARCHIVES "lib/static")
# Include (header) files install dir
set (ACQUIRE_INCLUDES "include/AcquireLib5")
# Shared files that stay static
set (ACQUIRE_FILES "share/AcquireLib5" CACHE STRING "Global installation directory")
# Shared files that stay static
set(ACQUIRE_EXPANDABLE_LOCAL_FILES "~/.AcquireLib5/" CACHE STRING "Local AcquireLib files (~ expands to home directory)")
string(REGEX REPLACE "~" "$ENV{HOME}" ACQUIRE_LOCAL_FILES ${ACQUIRE_EXPANDABLE_LOCAL_FILES})
file(MAKE_DIRECTORY ${ACQUIRE_LOCAL_FILES})
# CMake install files install dir
set (ACQUIRE_CMAKEFILES "include/AcquireLib5/cmake")
# CMake default install prefix
if ( CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT )
   set (CMAKE_INSTALL_PREFIX "$ENV{HOME}" CACHE PATH "Install prefix for AcquireLib" FORCE)
endif ( CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT )

# Define default host and port for broker in a new header file
set(DEFAULT_HOST 127.0.0.1 CACHE STRING "The host of the broker server")
#set(DEFAULT_HOST 127.0.0.1)
set(DEFAULT_PORT 10000 CACHE INTEGER "The port number of the broker server")
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/default_hosts.h "\n#ifndef __DEFAULT_HOSTS_H\n")
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/default_hosts.h "#define __DEFAULT_HOSTS_H\n\n")
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/default_hosts.h "#define DEFAULT_HOST \"")
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/default_hosts.h ${DEFAULT_HOST})
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/default_hosts.h "\"\n#define DEFAULT_PORT_STRING \"")
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/default_hosts.h ${DEFAULT_PORT})
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/default_hosts.h "\"\n#define DEFAULT_PORT ")
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/default_hosts.h ${DEFAULT_PORT})
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/default_hosts.h "\n\n#endif\n")

# Make sure to include the new header file in the compilation
include_directories(${CMAKE_CURRENT_BINARY_DIR})

set(SAVED_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--hash-style=both -fPIC -Wl,-dynamic-linker,${DYNAMIC_LINKER} -L. -Wl,-rpath-link,'$ORIGIN' -Wl,-rpath,'$ORIGIN'")
# SET THIS ON WHEN USING MAC OS
if (APPLE)
   set(CMAKE_EXE_LINKER_FLAGS "")
endif (APPLE)
if (WIN32)
   set(CMAKE_EXE_LINKER_FLAGS "")
endif (WIN32)

# Probably want a special switch to turn this off!
set(BROKER_ENC_KEY ${CMAKE_CURRENT_BINARY_DIR}/broker.enc)
set(BROKER_CHK_KEY ${CMAKE_CURRENT_BINARY_DIR}/broker.chk)

if ( DOWNLOAD_NEW_KEYS )
   file(REMOVE ${BROKER_ENC_KEY} ${BROKER_CHK_KEY})
endif ( DOWNLOAD_NEW_KEYS )

if ( DOWNLOAD_NEW_KEYS AND NOT INSECURE_TEST_KEYS )
   file(DOWNLOAD http://${DEFAULT_HOST}:${DEFAULT_PORT}/broker.enc ${BROKER_ENC_KEY} SHOW_PROGRESS STATUS STATENCKEY)
   if ( NOT STATENCKEY EQUAL 0 )
      message ( FATAL_ERROR "Could not download broker encryption key" )
   endif ( NOT STATENCKEY EQUAL 0 )
   file(DOWNLOAD http://${DEFAULT_HOST}:${DEFAULT_PORT}/broker.chk ${BROKER_CHK_KEY} SHOW_PROGRESS STATUS STATCHKKEY)
   if ( NOT STATCHKKEY EQUAL 0 )
      message ( FATAL_ERROR "Could not download broker checking key" )
   endif ( NOT STATCHKKEY EQUAL 0 )
endif ( DOWNLOAD_NEW_KEYS AND NOT INSECURE_TEST_KEYS )

if ( INSECURE_TEST_KEYS )
   message ( STATUS "***********************************************************" )
   message ( STATUS "*                                                         *" )
   message ( STATUS "* USING INSECURE KEYS FOR TESTING, USE THESE KEYS LOCALLY *" )
   message ( STATUS "*                 AND AT YOUR OWN RISK                    *" )
   message ( STATUS "*            INSTALLATION WILL BE DISABLED                *" )
   message ( STATUS "*                                                         *" )
   message ( STATUS "***********************************************************" )
   execute_process(COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/test_keys/broker.enc" ${CMAKE_CURRENT_BINARY_DIR}/)
   execute_process(COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/test_keys/broker.chk" ${CMAKE_CURRENT_BINARY_DIR}/)
   execute_process(COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/test_keys/broker_keydb.sql" ${CMAKE_CURRENT_BINARY_DIR}/)
endif ( INSECURE_TEST_KEYS )

set (CMAKE_BUILD_TYPE Debug)
set (CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake)

message(STATUS "LIBRARIES...")
set(CMAKE_FIND_LIBRARY_SUFFIXES .so)

find_package(Valgrind)
find_package(LibSSH2 REQUIRED)
find_package(SWIG REQUIRED)
find_package(PythonLibs REQUIRED)
find_package(PythonInterp REQUIRED)
if (UNIX)
   find_package(Threads)
endif (UNIX)
include(${SWIG_USE_FILE})
find_package(APR REQUIRED)
find_package(OpenSSL REQUIRED)
find_package(OpenSSLEngines)
find_library(LIBCRYPTO_LIBRARY NAMES crypto)

if (OPENSSL_ENGINES_FOUND)
    message(STATUS "Found OpenSSL engines: ${OPENSSL_ALL_ENGINE_LIBRARIES}")
endif (OPENSSL_ENGINES_FOUND)

if (LIBCRYPTO_LIBRARY)
   message(STATUS "Found libcrypto: ${LIBCRYPTO_LIBRARY}")
else (LIBCRYPTO_LIBRARY)
   message(FATAL_ERROR "Could not find libcrypto")
endif (LIBCRYPTO_LIBRARY)

set (INCLUDE_DIRS )
set (DEFINES )

if (APR_FOUND)
  set (INCLUDE_DIRS ${INCLUDE_DIRS} ${APR_INCLUDE_DIR})
else (APR_FOUND)
  message ( FATAL_ERROR "Could not find apr" )
endif (APR_FOUND)

if (APRUTIL_FOUND)
   set (INCLUDE_DIRS ${INCLUDE_DIRS} ${APRUTIL_INCLUDE_DIR})
else (APRUTILS_FOUND)
   message ( FATAL_ERROR "Could not find aprutils" )
endif (APRUTIL_FOUND)

if (OPENSSL_FOUND)
   set (INCLUDE_DIRS ${INCLUDE_DIRS} ${OPENSSL_INCLUDE_DIR})
else (OPENSSL_FOUND)
   message ( FATAL_ERROR "Could not find OpenSSL" )
endif (OPENSSL_FOUND)

if (LIBSSH2_FOUND)
   set (INCLUDE_DIRS ${INCLUDE_DIRS} ${LIBSSH2_INCLUDE_DIR})
else (LIBSSH2_FOUND)
   message ( FATAL_ERROR "Could not find LibSSH2" )
endif (LIBSSH2_FOUND)

set(ICONV_INCLUDE_DIR "" CACHE STRING "Optional include directory for iconv")
set (INCLUDE_DIRS ${INCLUDE_DIRS} ${ICONV_INCLUDE_DIR})
if (VALGRIND_FOUND)
   set (INCLUDE_DIRS ${INCLUDE_DIRS} ${VALGRIND_INCLUDE_DIR})
   add_definitions ( "-DVALGRIND_HACKS" )
endif (VALGRIND_FOUND)

if (WIN32)
add_definitions ( "-D__WIN32__" )
endif (WIN32)

#add_definitions ( "-DPASSDEFINE" "-D_GNU_SOURCE" )
add_definitions ( "-DGLIBCXX_FORCE_NEW" )
add_definitions ( "-DAPR_POOL_DEBUG=1" )
add_definitions ( "-DAPP_KEY_TAG=\"broker5automatedkey\"" )

include_directories(${INCLUDE_DIRS})
include_directories(${PYTHON_INCLUDE_PATH})
include_directories(${CMAKE_CURRENT_SOURCE_DIR})

if ( NOT LIBSSH2_VERSION_MAJOR GREATER 1 AND LIBSSH2_VERSION_MINOR LESS 2 )
   message ( FATAL_ERROR "LibSSH2 is too old (needed LibSSH2 >= 1.2, got LibSSH2 ${LIBSSH2_VERSION}" )
endif ( NOT LIBSSH2_VERSION_MAJOR GREATER 1 AND LIBSSH2_VERSION_MINOR LESS 2 )

include(CheckIncludeFiles)
CHECK_INCLUDE_FILES(openssl/ecdsa.h HAVE_SSL_WITH_ECDSA)
if ( NOT HAVE_SSL_WITH_ECDSA )
   message(FATAL_ERROR "Could not find ECDSA key support in OpenSSL. Install >= 0.9.8 or ensure that it is enabled at compile time.")
endif ( NOT HAVE_SSL_WITH_ECDSA )
CHECK_INCLUDE_FILES(${APR_INCLUDE_DIR}/apr_atomic.h HAVE_APR_ATOMIC)
if ( NOT HAVE_APR_ATOMIC )
   message(FATAL_ERROR "Could not find APR headers in ${APR_INCLUDE_DIR}.")
endif ( NOT HAVE_APR_ATOMIC )
set(CMAKE_EXTRA_INCLUDE_FILES ${APR_INCLUDE_DIR}/apr_atomic.h)
include(CheckLibraryExists)
CHECK_LIBRARY_EXISTS(apr-1 apr_random_add_entropy apr_random.h HAVE_APR_RANDOM_ADD_ENTROPY)
if ( NOT HAVE_APR_RANDOM_ADD_ENTROPY )
   message(FATAL_ERROR "Could not find apr_random_add_entropy function in ${APR_INCLUDE_DIR}/apr_random.h. APR should be >= 0.21 built with RNG support.")
endif ( NOT HAVE_APR_RANDOM_ADD_ENTROPY )
CHECK_LIBRARY_EXISTS(apr-1 apr_random_init apr_random.h HAVE_APR_RANDOM_INIT)
if ( NOT HAVE_APR_RANDOM_INIT )
   message(FATAL_ERROR "Could not find apr_random_init function in ${APR_INCLUDE_DIR}/apr_random.h. APR should be >= 0.21 built with RNG support.")
endif ( NOT HAVE_APR_RANDOM_INIT )
CHECK_LIBRARY_EXISTS(apr-1 apr_crypto_sha256_new apr_random.h HAVE_APR_CRYPTO_SHA256_NEW)
if ( NOT HAVE_APR_CRYPTO_SHA256_NEW )
   message(FATAL_ERROR "Could not find apr_crypto_sha256_new function in ${APR_INCLUDE_DIR}/apr_random.h. APR should be >= 0.21 built with RNG support.")
endif ( NOT HAVE_APR_CRYPTO_SHA256_NEW )
CHECK_LIBRARY_EXISTS(apr-1 apr_random_standard_new apr_random.h HAVE_APR_RANDOM_STANDARD_NEW)
if ( NOT HAVE_APR_RANDOM_STANDARD_NEW )
   message(FATAL_ERROR "Could not find apr_random_standard_new function in ${APR_INCLUDE_DIR}/apr_random.h. APR should be >= 0.21 built with RNG support.")
endif ( NOT HAVE_APR_RANDOM_STANDARD_NEW )
CHECK_LIBRARY_EXISTS(apr-1 apr_random_secure_ready apr_random.h HAVE_APR_RANDOM_SECURE_READY)
if ( NOT HAVE_APR_RANDOM_SECURE_READY )
   message(FATAL_ERROR "Could not find apr_random_secure_ready function in ${APR_INCLUDE_DIR}/apr_random.h. APR should be >= 0.21 built with RNG support.")
endif ( NOT HAVE_APR_RANDOM_SECURE_READY )
CHECK_LIBRARY_EXISTS(apr-1 apr_random_secure_bytes apr_random.h HAVE_APR_RANDOM_SECURE_BYTES)
if ( NOT HAVE_APR_RANDOM_SECURE_BYTES )
   message(FATAL_ERROR "Could not find apr_random_secure_bytes function in ${APR_INCLUDE_DIR}/apr_random.h. APR should be >= 0.21 built with RNG support.")
endif ( NOT HAVE_APR_RANDOM_SECURE_BYTES )
CHECK_LIBRARY_EXISTS(apr-1 apr_atomic_xchgptr apr_atomic.h HAVE_ATOMIC_EXCHANGE_POINTER)

file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "\n#ifndef __CONFIG_H\n")
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "#define __CONFIG_H\n\n")
if ( INSECURE_TEST_KEYS )
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "#define ACQUIRE_STATIC_DIR \"")
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h ${CMAKE_CURRENT_SOURCE_DIR}/scripts)
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "\"\n#define ACQUIRE_DYNAMIC_DIR \"")
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h ${CMAKE_CURRENT_BINARY_DIR})
   set(TEST_SCRIPTS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/scripts)
else ( INSECURE_TEST_KEYS )
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "#define ACQUIRE_STATIC_DIR \"")
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h ${CMAKE_INSTALL_PREFIX}/${ACQUIRE_FILES})
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "\"\n#define ACQUIRE_DYNAMIC_DIR \"")
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h ${ACQUIRE_EXPANDABLE_LOCAL_FILES})
   set(TEST_SCRIPTS_DIR ${CMAKE_INSTALL_PREFIX}/${ACQUIRE_FILES})
endif ( INSECURE_TEST_KEYS )
file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "\"\n")
if ( HAVE_ATOMIC_EXCHANGE_POINTER )
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "#define ATOMIC_EXCHANGE_POINTER\n")
endif ( HAVE_ATOMIC_EXCHANGE_POINTER )

if ( LOG_MESSAGE_TO_FILE )
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "#define ACQUIRE_LOG_FILE\n")
endif ( LOG_MESSAGE_TO_FILE )
if ( INSECURE_PASSWORDS )
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "#define USE_BUILTIN_INSECURE_PASSWORDS\n")
endif ( INSECURE_PASSWORDS )
if ( INSECURE_TEST_KEYS )
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "#define USE_TEST_CLUSTER\n")
   file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "#define TEST_CLUSTER_XML \"${CMAKE_CURRENT_SOURCE_DIR}/scripts/test_cluster.xml\"\n")
endif ( INSECURE_TEST_KEYS )

file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h "\n#endif\n")

set ( ACQUIRE_SWIG_INTERFACES
       acquirepy.i )

set ( ACQUIRE_LIB_SOURCES
       aprtools/APRBucketBrigade.cpp
       aprtools/APRDOMDocument.cpp
       aprtools/APRFile.cpp
       aprtools/APRPRNG.cpp
       aprtools/APRTable.cpp
       crypt/AbstractKey.cpp
       crypt/AESDecrypt.cpp
       crypt/AESEncrypt.cpp
       crypt/AESSymmetricKey.cpp
       crypt/CryptOChain.cpp
       crypt/DecryptWrapper.cpp
       crypt/DSAChecking.cpp
       crypt/DSAKeyPairGenerator.cpp
       crypt/DSAPrivateKey.cpp
       crypt/DSAPublicKey.cpp
       crypt/DSASigning.cpp
       crypt/ECDSAChecking.cpp
       crypt/ECDSAKeyPairGenerator.cpp
       crypt/ECDSAPrivateKey.cpp
       crypt/ECDSAPublicKey.cpp
       crypt/ECDSASigning.cpp
       crypt/EncryptWrapper.cpp
       crypt/GZCompress.cpp
       crypt/GZDecompress.cpp
       crypt/PrivateKey.cpp
       crypt/PublicKey.cpp
       crypt/RSAChecking.cpp
       crypt/RSADecrypt.cpp
       crypt/RSAEncrypt.cpp
       crypt/RSAKeyPairGenerator.cpp
       crypt/RSAPrivateKey.cpp
       crypt/RSAPublicKey.cpp
       crypt/RSASigning.cpp
       crypt/SymmetricKey.cpp
       db/Actor.cpp
       db/ActorsDB.cpp
       db/DataStore.cpp
       db/DBUtils.cpp
       db/Key.cpp
       db/KeyTableView.cpp
       db/KeyDB.cpp
       db/NetworkDB.cpp
       db/NetworkDBFromXML.cpp
       db/PendingDB.cpp
       db/SQLiteAutoLock.cpp
       db/SQLiteDB.cpp
       db/SQLiteLockCounter.cpp
       db/SQLiteTransactor.cpp
       db/WorkInstance.cpp
       iface/APRInterface.cpp
       iface/LibSSH2Interface.cpp
       iface/SSLInterface.cpp
       iface/SQLiteInterface.cpp
       iface/ZlibInterface.cpp
       net/BlockWriteClient.cpp
       net/BlockWriteServer.cpp
       net/Broker5Client.cpp
       net/Broker5Server.cpp
       net/BrokerMessage.cpp
       net/CongestionControl.cpp
       net/EncMessage.cpp
       net/HTTPServer.cpp
       net/RateControl.cpp
       net/TCPClient.cpp
       net/TCPServer.cpp
       net/UDPSend.cpp
       net/UDPServer.cpp
       resolver/Resolver.cpp
       resolver/LocalResolver.cpp
       resolver/RemoteResolver.cpp
       sqlite/sqlite3.c
       ssh/ForwardServer.cpp
       ssh/PersistentForwardChannel.cpp
       ssh/RemoteSSHKeyFile.cpp
       ssh/SCPReceiveChannel.cpp
       ssh/SCPSendChannel.cpp
       ssh/SecurityChain.cpp
       ssh/SecurityTokenFile.cpp
       ssh/SecurityTokenInteractive.cpp
       ssh/SecurityTokenKey.cpp
       ssh/SecurityTokenPassword.cpp
       ssh/ShellChannel.cpp
       ssh/SSHChannel.cpp
       ssh/SSHClient.cpp
       ssh/SSHClientWrapper.cpp
       ssh/SSHTelescope.cpp
       utils/BaseConvert.cpp
       utils/Hash.cpp
       utils/Prompt.cpp
       utils/RunningWorkProcess.cpp
       utils/StreamFromDirectory.cpp
       utils/StreamToDirectory.cpp
       utils/StringUtils.cpp
       acquire_common_private.cpp
       acquire_common.cpp
       acquire_client.cpp
       acquire_compute.cpp
    )

set ( BROKER_SOURCES
       main_broker.cpp
    )

set ( NEWCLIENT_SOURCES
#      acquire_client.cpp
      main_newclient.cpp
    )

set ( COMPUTE_SOURCES
       main_compute.cpp
    )

set ( TEST_SERVER_SOURCES
       tests/test_server.cpp
       tests/testHTTPServer.cpp
       tests/testTCPServer.cpp
       tests/testUDPServer.cpp
    )
    
set ( TEST_CLIENT_SOURCES
       tests/test_client.cpp
       tests/testAESKeys.cpp
       tests/testCryptOChain.cpp
       tests/testDSAKeys.cpp
       tests/testECDSAKeys.cpp
       tests/testEncDecWrapper.cpp
       tests/testGZCompress.cpp
       tests/testRSAKeys.cpp
       tests/testSSHClient.cpp
       tests/testUDPSend.cpp
    )

set (LINK_LIBRARIES )

if (APRUTIL_FOUND)
   set (LINK_LIBRARIES ${LINK_LIBRARIES} ${APRUTIL_LIBRARY})
endif (APRUTIL_FOUND)

if (APR_FOUND)
  set (LINK_LIBRARIES ${LINK_LIBRARIES} ${APR_LIBRARY})
endif (APR_FOUND)

if (LIBSSH2_FOUND)
   set (LINK_LIBRARIES ${LINK_LIBRARIES} ${LIBSSH2_LIBRARY})
endif (LIBSSH2_FOUND)

if (OPENSSL_FOUND)
   set (LINK_LIBRARIES ${LINK_LIBRARIES} ${OPENSSL_LIBRARIES} ${LIBCRYPTO_LIBRARY})
endif (OPENSSL_FOUND)

if (UNIX)
   set (LINK_LIBRARIES ${LINK_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT})
endif (UNIX)

if (BUILD_STATIC_LIBRARIES)
   add_library(AcquireLib STATIC ${ACQUIRE_LIB_SOURCES})
else (BUILD_STATIC_LIBRARIES)
   add_library(AcquireLib SHARED ${ACQUIRE_LIB_SOURCES})
endif (BUILD_STATIC_LIBRARIES)

if (BUILD_STATIC)
   find_library(LIBCRYPT_LIBRARY NAMES crypt)
   find_library(LIBFREEBL3_LIBRARY NAMES freebl3)
   find_library(LIBRT_LIBRARY NAMES rt)
   find_library(LIBEXPAT_LIBRARY NAMES expat)

   target_link_libraries(AcquireLib ${LINK_LIBRARIES} ${LIBSTDCXX_LIBRARY} ${LIBGCC_LIBRARY} dl z m c)
else (BUILD_STATIC)
   target_link_libraries(AcquireLib ${LINK_LIBRARIES})
endif (BUILD_STATIC)

SET_SOURCE_FILES_PROPERTIES(${ACQUIRE_SWIG_INTERFACES} PROPERTIES CPLUSPLUS ON)
#SET_SOURCE_FILES_PROPERTIES(${ACQUIRE_SWIG_INTERFACES} PROPERTIES SWIG_FLAGS "-includeall")
SWIG_ADD_MODULE(acquirepy python ${ACQUIRE_SWIG_INTERFACES} ${ACQUIRE_LIB_SOURCES})
SWIG_LINK_LIBRARIES(acquirepy ${PYTHON_LIBRARIES} ${LINK_LIBRARIES})

if ( BUILD_SPECIAL_COMPUTE )
   add_custom_target(pack_acquirepy
      COMMAND /bin/sh ${CMAKE_CURRENT_SOURCE_DIR}/scripts/ldd_archive.sh _acquirepy.so ${CMAKE_CURRENT_SOURCE_DIR}/scripts/glibc_patch.c ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/scripts/compute.py
      COMMENT "Packing up acquirepy..."
   )
   add_custom_target(copy_acquirepy_package
      COMMAND ${CMAKE_COMMAND} -E copy _acquirepy.so.tar.gz hosted_files/_acquirepy
      COMMENT "Copying acquirepy package..."
   )
   add_dependencies(pack_acquirepy _acquirepy)
   add_dependencies(copy_acquirepy_package pack_acquirepy)
endif ( BUILD_SPECIAL_COMPUTE )

add_executable(broker ${BROKER_SOURCES})
target_link_libraries(broker AcquireLib)

if ( BUILD_TESTS )
   add_executable(test_server ${TEST_SERVER_SOURCES})
   target_link_libraries(test_server AcquireLib)

   add_executable(test_client ${TEST_CLIENT_SOURCES})
   target_link_libraries(test_client AcquireLib)
   
   execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory tests)
   execute_process(COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/scripts/test_client.py ${CMAKE_CURRENT_BINARY_DIR}/tests/)
   string(RANDOM RANDOM_USER_BLOB)
   configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/test_credentials.py.in ${CMAKE_CURRENT_BINARY_DIR}/tests/test_credentials.py)
endif ( BUILD_TESTS )

execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory hosted_files)
execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory $ENV{HOME}/.AcquireLib/)
execute_process(COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/scripts/acquire.py ${CMAKE_CURRENT_BINARY_DIR}/)
execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory test_workpacket)
execute_process(COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/scripts/test_workpacket_go.sh ${CMAKE_CURRENT_BINARY_DIR}/test_workpacket/go.sh)
execute_process(COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/scripts/test_workpacket_process.py ${CMAKE_CURRENT_BINARY_DIR}/test_workpacket/)

configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/bootstrap.sh.in ${CMAKE_CURRENT_BINARY_DIR}/hosted_files/bootstrap.sh)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/python_bootstrap.sh.in ${CMAKE_CURRENT_BINARY_DIR}/hosted_files/python_bootstrap.sh)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/queue.sh.in ${CMAKE_CURRENT_BINARY_DIR}/hosted_files/queue.sh)

add_executable(acquire ${NEWCLIENT_SOURCES})
if ( DOWNLOAD_NEW_KEYS )
   add_dependencies(acquire KEYDB)
endif ( DOWNLOAD_NEW_KEYS )
target_link_libraries(acquire AcquireLib)

execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory results_files)
execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory workarea_files)

add_executable(compute ${COMPUTE_SOURCES})
if ( BUILD_SPECIAL_COMPUTE )
   # Forces python library to archive
   add_dependencies(compute copy_acquirepy_package)
endif ( BUILD_SPECIAL_COMPUTE )
target_link_libraries(compute AcquireLib)

if ( BUILD_SPECIAL_COMPUTE )
   add_custom_command(
      TARGET compute
      POST_BUILD
      COMMAND /bin/sh ${CMAKE_CURRENT_SOURCE_DIR}/scripts/ldd_archive.sh compute ${CMAKE_CURRENT_SOURCE_DIR}/scripts/glibc_patch.c
   )
#${CMAKE_CURRENT_SOURCE_DIR}/glibc_patch.c
   add_custom_command(
      TARGET compute
      POST_BUILD
      COMMAND ${CMAKE_COMMAND} -E copy compute.tar.gz hosted_files/compute
   )
endif ( BUILD_SPECIAL_COMPUTE )

if ( INSECURE_TEST_KEYS )
   message ( STATUS "***********************************************************" )
   message ( STATUS "*                INSTALLATION DISABLED                    *" )
   message ( STATUS "* USING INSECURE KEYS FOR TESTING, USE THESE KEYS LOCALLY *" )
   message ( STATUS "*                 AND AT YOUR OWN RISK                    *" )
   message ( STATUS "*                                                         *" )
   message ( STATUS "***********************************************************" )
else ( INSECURE_TEST_KEYS )
   install( TARGETS AcquireLib acquire compute broker EXPORT AcquireLibrary
            RUNTIME DESTINATION ${ACQUIRE_BIN}
            LIBRARY DESTINATION ${ACQUIRE_LIBS}
            ARCHIVE DESTINATION ${ACQUIRE_ARCHIVES}
         )
         
   install( FILES ${CMAKE_CURRENT_SOURCE_DIR}/acquire_client.h
                  ${CMAKE_CURRENT_BINARY_DIR}/default_hosts.h
                  ${CMAKE_CURRENT_BINARY_DIR}/acquire_config.h
            DESTINATION ${ACQUIRE_INCLUDES} )

   install( FILES "${CMAKE_CURRENT_BINARY_DIR}/hosted_files/bootstrap.sh"
                  "${CMAKE_CURRENT_BINARY_DIR}/hosted_files/python_bootstrap.sh"
                  "${CMAKE_CURRENT_BINARY_DIR}/hosted_files/queue.sh"
                  "${CMAKE_CURRENT_BINARY_DIR}/hosted_files/compute"
                  "${CMAKE_CURRENT_BINARY_DIR}/hosted_files/_acquirepy"
            DESTINATION ${ACQUIRE_LOCAL_FILES}/hosted_files/ )
            
   install( FILES "${CMAKE_CURRENT_SOURCE_DIR}/scripts/fake_queue_test.py"
                  "${CMAKE_CURRENT_SOURCE_DIR}/scripts/test_cluster.xml"
                  "${CMAKE_CURRENT_SOURCE_DIR}/scripts/example_clusters.xml"
                  "${CMAKE_CURRENT_BINARY_DIR}/test_client"
                  "${CMAKE_CURRENT_BINARY_DIR}/test_server"
            DESTINATION ${ACQUIRE_FILES}/ )
            
   install( FILES "${BROKER_ENC_KEY}"
                  "${BROKER_CHK_KEY}"
            DESTINATION ${ACQUIRE_LOCAL_FILES}/ )

   install( EXPORT AcquireLibrary
            NAMESPACE Acquire_
            DESTINATION ${ACQUIRE_CMAKEFILES} )
endif ( INSECURE_TEST_KEYS )
